<?php
/**
 * menus
 *
 * @version:	0.1
 * @package:	global
 * @author:		alex_ez
 * @created:	30.11.2010
 *
 * @copyright:	(c) 2010 alex <qfox@ya.ru> yaroshevich aka alex_ez. All rights reserved.
 */


class menus_controller extends controller
{
	protected $quantity;
	
	public function on_start( )
	{
		$this->model = new menus( );
	}

	/*public function page_index( $p, $o )
	{
		$tag = isset($p['tag']) ? $p['tag'] : ( isset($o['tag']) ? $o['tag'] : 'front' );
		if( $tag != 'front' )
			$tag = texo::latinate( $tag, '/' );
		
		$v = $this ->model ->by_tag( trim( $tag, '/' ), 0 );
		if( is_null( $v ) )
			response::instance( ) ->notfound( );
			//return 'page not found.';
		
		$meta = (array)(json::decode( $v['meta'] ));
		$meta += array( 'title' => $v['title'] );
		$meta += (array)(isset($o['meta'])?$o['meta']:array());
		$this->meta = $meta;
		
		if( $v['title'] )
		$this ->crumbs[] = $v['title'];

		if( isset($p['return']) && $p['return'] )
			return $v;
		
		return sprintf( '<div class="static-body static-%1$s-container-body">%2$s</div>', str_replace( array( '/', '_', '.' ), '-', $tag ), $v['body'] );
	}
	
	public function page_all( $p, $o )
	{
		
		$page = (isset($p['page'])) ? (int)$p['page'] : 1;
		
		$list = $this ->model ->by( '`tag` like "articles/%"', 'title-', array( ($page-1)*$this ->quantity, $this ->quantity) );
		$found_rows = $this ->model ->get_found_rows( );
		$total_pages = ( intval( $found_rows / $this ->quantity) ) + (( $found_rows % $this ->quantity)>0 ? 1:0 );
		
		$r = array( 'list' => $list, 'total_pages' => $total_pages, 'current_page' => $page );
		
		return $r;
	}*/
	
	public function block_menu( $p )
	{
		$url = isset($p['url']) ? $p['url'] : request::instance()->get_uri();
		$debug = isset($p['debug']);

		$links = $this->links($url);
		
		if( empty($links) )
			return '';
		
		return $p + compact('links');
	}
	
	protected function links( $url )
	{
		$pages = $this->model->by(array('state'=>'on'),'order+');
		$r = array();
		
		$is_dev = request::instance()->is_developer();
		
		foreach( $pages as $v )
		if( $v['state'] !== 'off' )
		{
			$m = array( );
			$_r = ( $v['path'][0] == '@' )
				? ( preg_match( str_replace( '/$', '/?$', $v['path'] ), $url, $m ) )
				: ( $v['path'] == $url || rtrim($v['path'],'/') == $url );
			
			$v['selected'] = ($v['url'] == $url);
			// debug
			//if( $is_dev )
			//	$debug[ ( $v['url']{0} == '@' ) ? 'regs' : 'urls' ][] = &$v['url'];
			
			if( $_r )
				$r[$v['id']] = $v;
		}

		// empty if no pages found
		return $r;
	}


	public function exists( $tag, $type = 'page' )
	{
		if( strpos( 'page,block', $type ) === false ) $type == 'page';
		$prefix = ( $type == 'page' ) ? '' : '$';
		
		return !!( $this ->model ->count( array( 'tag' => $prefix.$tag ) ) );
	}
}

?>